<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true">
				<el-form-item>
					<el-input v-model="keyword" placeholder="姓名"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="keywordQuery">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
      </el-form>
		</el-col>

		<!--列表-->
		<el-table :data="departments" highlight-current-row v-loading="listLoading"
              @selection-change="selsChange" @row-dblclick="show" style="width: 100%;">
      <!-- 批量删除：type="selection - 选项 -->
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
      <el-table-column prop="sn" label="部门编号" width="100">
      </el-table-column>
			<el-table-column prop="name" label="名称" width="100">
			</el-table-column>
			<el-table-column prop="state" label="状态" width="100">
        <template slot-scope="scope">
          <span style="color: green" v-if="scope.row.state==1">正常</span>
          <span style="color: red" v-else>停用</span>
        </template>
			</el-table-column>
			<el-table-column prop="manager.username" label="部门经理" width="100">
			</el-table-column>
			<el-table-column prop="parent.name" label="上级部门" min-width="100">
			</el-table-column>
			<el-table-column label="操作">
				<template scope="scope">
					<el-button size="small" @click="handleSave(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange"
                     :page-size="pageSize" :total="totals" :current-page="currentPage" style="float:right;">
			</el-pagination>
		</el-col>

		<!--编辑或新增界面-->
		<el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false">
			<el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
				<el-form-item label="部门编号" prop="sn">
					<el-input v-model="saveForm.sn" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="部门名称" prop="name">
					<el-input v-model="saveForm.name" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="部门状态">
					<el-radio-group v-model="saveForm.state">
						<el-radio class="radio" :label="1">启用</el-radio>
						<el-radio class="radio" :label="0">禁用</el-radio>
					</el-radio-group>
        </el-form-item>
        <el-form-item label="部门经理">
          <el-select v-model="saveForm.manager_id" placeholder="请选择">
            <el-option
                v-for="item in managers"
                :label="item.username"
                :value="item.id"
                >
              <span style="float: left">{{ item.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上级部门">
          <el-cascader v-model="saveForm.parent_id"
              :options="deptTree"
              :props="{ checkStrictly: true,label:'name',value:'id',emitPath:false }"
              clearable></el-cascader>
        </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click.native="saveFormVisible = false">取消</el-button>
          <el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
        </div>
		</el-dialog>

    <!--抽屉表格-->
    <el-drawer
        title="详细信息"
        :visible.sync="table"
        direction="rtl"
        size="50%">
      <el-table :data="gridData">
          <el-table-column type="selection" width="55">
          </el-table-column>
          <el-table-column type="index" width="60">
          </el-table-column>
          <el-table-column prop="sn" label="部门编号" width="100">
          </el-table-column>
          <el-table-column prop="name" label="名称" width="100">
          </el-table-column>
          <el-table-column prop="state" label="状态" width="100">
            <template slot-scope="scope">
              <span style="color: green" v-if="scope.row.state==1">正常</span>
              <span style="color: red" v-else>停用</span>
            </template>
          </el-table-column>
          <el-table-column prop="manager_id" label="部门经理" width="100">
          </el-table-column>
          <el-table-column prop="parent_id" label="上级部门" min-width="100">
          </el-table-column>
        </el-table>
    </el-drawer>

  </section>
</template>

<script>
	export default {
		data() {
			return {

			  //1.分页相关的数据
        departments: [],     //绑定到显示数据的表格
        totals: 0,          //总数量 - 计算分页栏
        currentPage: 1,     //当前页 - 分页栏默认当前页显示
        pageSize: 5,        //每页显示的条数  - 计算分页栏
        listLoading: false, //盲等框

        //2.高级查询
        keyword:'',

        //3.批量删除
        sels: [],//列表选中列

        //4.新增和编辑
				saveFormVisible: false,//编辑界面是否显示
        title:'', //显示的模态框名称
				saveLoading: false,
        //5.验证规则
				saveFormRules: {
					sn: [
						{ required: true, message: '请输入部门编号', trigger: 'blur' }
					],
					name: [
						{ required: true, message: '请输入部门名称', trigger: 'blur' }
					]
				},
				//6.新增和修改的模块框数据
				saveForm: {
					id: null,
          sn: '',
					name: '',
          state: 0,
          manager_id: null,
          parent_id: null
				},
        //7.下拉框 - 部门经理数据
        managers:[],
        //8.无限级数 - 保存部门树
        deptTree:[],
        //9.抽屉
        table: false,
        gridData:[],
			}
		},
		methods: {
      //1.分页查询 - 获取部门列表
      getDepartments() {
        //传递的参数
        let para = {
          currentPage: this.currentPage,
          pageSize: this.pageSize,
          keyword: this.keyword
        };
        //页面一加载就显示加载框
        this.listLoading = true;
        this.$http.post("/department",para).then(res => {
          //赋值总数量
          this.totals = res.data.totals;
          //当前页的数据
          this.departments = res.data.data;
          //关闭加载框
          this.listLoading = false;
        }).catch(res => {
          this.$message.error('系统繁忙，请稍后重试!!!');
        })
      },
      //2.点击页数触发
      handleCurrentChange(val) {
        //当前页
        this.currentPage = val;
        this.getDepartments();
      },
      //3.高级查询
      keywordQuery(){
        this.currentPage = 1;
        this.getDepartments();
      },
      //4.删除
      handleDel: function (index, row) {
        this.$confirm('确认删除该记录吗?', '提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true; //打开盲等框
          this.$http.delete("department/"+row.id).then(res=>{
            if (res.data.success){
              //总页数
              let totalPage = Math.ceil(this.totals/this.pageSize);
              //如果是最后一页的最后一条数据，并且当前页不是第一页，就跳转到上一页
              if (this.sels.length===0 && this.currentPage != 1){
                this.currentPage = this.currentPage-1;
              }
              this.getDepartments(); //重新获取数据
            }else {
              this.$message.error('系统繁忙，请稍后重试!!![500]');
            }
            this.listLoading = false; //关闭盲等框
          }).catch(res=>{
              this.$message.error('系统繁忙，请稍后重试!!!');
          })
        }).catch(() => {

        });
      },
      //5.批量删除，触发时改变
      selsChange: function (sels) {
        this.sels = sels;
      },
      //6.批量删除
      batchRemove: function () {
        var ids = this.sels.map(item => item.id);
        this.$confirm('确认删除选中记录吗？', '提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true;
          this.$http.patch("department",ids).then(res => {
            if (res.data.success){
              this.currentPage = 1;
              this.getDepartments();
            }else {
              this.$message.error("系统繁忙!【500】")
            }
          }).catch(res=>{
            this.$message.error("系统繁忙!【400,404】")
          })
        }).catch(() => {

        });
      },
			//7.点击编辑按钮弹出修改对话框
			handleSave: function (index, row) {
        //对话框名称
        this.title = '修改部门信息';
				//回显表格数据
				this.saveForm = Object.assign({}, row);
        //下拉框回显部门经理
        this.getManager();
        //无限级数部门树
        this.getdeptTree();
        //打开编辑对话框
        this.saveFormVisible = true;
			},
			//8.点击新增按钮弹出对话框
			handleAdd: function () {
        this.title = '新增部门';
				//清空对话框的表格数据
				this.saveForm = {
          id: null,
          sn: '',
          name: '',
          state: 0,
          manager_id: null,
          parent_id: null
        };
				//下拉框回显部门经理
				this.getManager();
        //无限级数部门树
        this.getdeptTree();
        //打开新增对话框
        this.saveFormVisible = true;
			},
			//9.新增和修改
      saveSubmit: function () {
        this.$refs.saveForm.validate((valid) => {
          if (valid) {
            this.$confirm('确认提交吗？', '提示', {}).then(() => {
              this.saveLoading = true;
              let para = Object.assign({}, this.saveForm);
              this.$http.put("department",para).then(res=>{
                if (res.data.success){
                  this.getDepartments();
                }else {
                  this.$message.error("我错啦!【500】")
                }
                this.saveFormVisible = false;
                this.saveLoading = false;
              }).catch(res=>{
                  this.$message.error("我错啦!【400,404】")

              })
            });
          }
        });
      },
      //10.查询所有经理数据
      getManager(){
        this.$http.get("employee").then(res=>{
          this.managers = res.data;
        })
      },
      getdeptTree(){
        this.$http.get("department/deptTree").then(res=>{
          this.deptTree = res.data;
        });
      },

      //11.抽屉
      show(row){
        this.listLoading = true;
        this.drawerId = row.id;
        this.$http.get("/department/"+this.drawerId).then(res=>{
          this.gridData.pop(res.data);
          this.gridData.push(res.data);
          this.listLoading = false;
          this.table = true
        }).catch(res=>{

        })
      }
		},
		mounted() {
			this.getDepartments();
		}
	}


</script>

<style scoped>

</style>